// dependencies plugins
var gulp = require('gulp'),
    sprity = require('sprity'),
    browserSync = require('browser-sync'),
    reload = browserSync.reload,
    url = require('url'),
    proxy = require('proxy-middleware'),
    plugins = require('gulp-load-plugins')(),
	webpack = require("webpack"),
	webpackConfig = require("./webpack.config.js");

var filePath = {
    swig: './src/templates/*.html',
    swigTpm: './src/templates/static/*.html',
    sass: ['./src/sass/*.scss', './src/sass/*/*.scss','./src/sass/*.css'],
    lib_common_js: ['./src/js/lib/common/*.js'],
    lib_js: './src/js/lib/**.js',

    //add by levy, 引用别人的控件
    calendar_js: ['./src/js/lib/calendar/moment.min.js','./src/js/lib/calendar/jquery.min.js','./src/js/lib/calendar/fullcalendar.js','./src/js/lib/calendar/lang.js'],
    dtpicker_js: ['./src/js/lib/dtpicker/picker.js','./src/js/lib/dtpicker/dtpicker.js'],

    img: ['./src/public/images/*.*','./src/public/images/**/*.*'],
    static: ['./src/public/staticJson/**.*','./src/public/fonts/**.*'],
    sprite_img: './src/public/images/',
    dist_css: './build/public/css',
    dist_lib_js: './build/public/js/lib',
    dist_swig: './build/html',
    dist_img: './build/public/images',
    dist_static: ['./build/public/staticJson','./build/public/fonts'],
    normal_img: './src/public/images/',
    tmp: './.tmp/',
    build: './build/'
},
    watchPath = {
        swig: 'src/templates/*.html',
        swigTpm: 'src/templates/common/*.html',
        sass: ['src/sass/*.scss', 'src/sass/*/*.scss'],
        lib_common_js: ['src/js/lib/common/*.js']
    },
    sprite_file_name = ['index'];

    const DEV = process.env.DEV || '',
          ENV = process.env.RUN_ENV || 'dev', //看 jenkins 配置
          PRO = 'production';



/*---------- clean ----------*/
gulp.task('clean', function ( ) {
    return gulp.src([filePath.build,filePath.tmp], {read: false}).pipe(plugins.clean());
});

/* ------------- build ------------- */
gulp.task("webpack", function() {
    var myConfig = Object.create(webpackConfig),
		compiler = webpack( //这里也build了一次啊。跟文档说的不一样啊。
			myConfig
			, function(err, stats) {
                outputInfo(stats);
			});

    if(ENV == 'dev')
        compiler.watch({ // watch options:
            aggregateTimeout: 300, // wait so long for more changes
            poll: true // use polling instead of native watchers
            // pass a number to set the polling interval
        }, function(err, stats) {
            outputInfo(stats);
        });

    var outputInfo = function (stats) {
        var str = stats.toString();
        if(str.indexOf('ERROR') > -1){
            console.log(str);
        }
        else {
            console.log('webpack builds successfully ' + new Date().toLocaleString());
        }
    }
});

gulp.task('sass', function ()  {
    var gulpTask = gulp.src(filePath.sass)
        .pipe(plugins.plumber({
            errorHandler: function(err) {
                // display the error message
                console.log(err);
                // end the errored task
                this.emit('end') }
        }))
        .pipe(plugins.sass({
            outputStyle: 'compressed'
        }))
        .pipe(plugins.autoprefixer())
        .pipe(plugins.plumber.stop());

    gulpTask = DEV ? gulpTask : gulpTask.pipe(plugins.cached('sass_compile'));
    gulpTask = gulpTask.pipe(gulp.dest(filePath.dist_css));

    gulpTask = !DEV ? gulpTask.pipe(plugins.notify({message: 'sass completed!'})) : gulpTask;
    return gulpTask;
});

// common.min.js 压缩
gulp.task('distCommon', function () {
    var lib_ary = [ 'common'];
    filePath.lib_common_js.map( function ( v, i ) {
        var gulpTask = gulp.src(v);
        gulpTask = ENV ==  PRO?
            gulpTask.pipe(plugins.replace(/lf.prod=0/, "lf.prod=1"))
            : gulpTask;

        gulpTask = gulpTask.pipe(plugins.concat(lib_ary[i]+'.min.js'))
            .pipe(plugins.plumber({
                errorHandler: function(err) {
                    // display the error message
                    console.log(err);
                    // end the error task
                    this.emit('end') }
            }));

        gulpTask = gulpTask.pipe(plugins.babel({
                presets: ['es2015', 'react']
            }))
            .pipe(plugins.uglify())
            //.pipe(plugins.sourcemaps.write('./maps'))
            .pipe(gulp.dest(filePath.dist_lib_js));

        !DEV ? gulpTask.pipe(plugins.notify({message: 'distCommon completed!'})) : gulpTask;
    });

    var calendar = gulp.src(filePath.calendar_js);
    calendar.pipe(plugins.concat('calendar.min.js'))
        .pipe(plugins.plumber({
            errorHandler: function(err) {
                // display the error message
                console.log(err);
                // end the error task
                this.emit('end') }
        }))
        .pipe(plugins.uglify())
        .pipe(gulp.dest(filePath.dist_lib_js))
        .pipe(plugins.notify({message: 'calendar.min.js done!'}));

    //时间控件
    var dtpicker = gulp.src(filePath.dtpicker_js);
    dtpicker.pipe(plugins.concat('dtpicker.min.js'))
        .pipe(plugins.plumber({
            errorHandler: function(err) {
                // display the error message
                console.log(err);
                // end the error task
                this.emit('end') }
        }))
        .pipe(plugins.uglify())
        .pipe(gulp.dest(filePath.dist_lib_js))
        .pipe(plugins.notify({message: 'dtpicker.min.js done!'}));

});

// 平移不公共js
gulp.task('distStaticLibJs', function () {
    return gulp.src(filePath.lib_js)
        .pipe(gulp.dest(filePath.dist_lib_js))
        .pipe(plugins.changed(filePath.dist_lib_js))
        .pipe(plugins.notify({message: 'distStaticLibJs completed!'}));
});

// 编译swig模板
gulp.task('distSwig', function () {
    var gulpTask = gulp.src(filePath.swig)
            .pipe(plugins.plumber({
                errorHandler: function(err) {
                    // display the error message
                    console.log(err);
                    // end the error task
                    this.emit('end') }
            }));
    
    // 检测模板文件是否发生更改
    if(ENV == 'dev')
         gulpTask.pipe(plugins.changed( filePath.dist_swig, {extension: '.html'}));

    gulpTask = gulpTask.pipe(plugins.swig({defaults: { cache: false }}));

    // 生产环境替换react.js
    // if(ENV != 'dev')
    //     gulpTask.pipe(plugins.replace(/..\/public\/js\/lib\/react.js/, '//cdn.bootcss.com/react/0.13.1/react.min.js'));

    gulpTask = gulpTask.pipe(gulp.dest(filePath.dist_swig));

    gulpTask = !DEV ? gulpTask.pipe(plugins.notify({message: 'distSwig completed!'})) : gulpTask;
    return gulpTask;
});

// icon sprity 处理
gulp.task('sprity', function () {

    sprite_file_name.map( function (v) {
        sprity.src({
                src: filePath.sprite_img + v + '/*.*',
                name: v + '-icons',
                cssPath: filePath.dist_img,
                style: './_icons.scss',
                processor: 'sass',
                prefix: 'liefeng-icon'
            })
            .pipe(plugins.if('*.png', gulp.dest(filePath.normal_img), gulp.dest('./src/sass/static/')))
            .pipe(plugins.notify({message: 'sprity completed!'}));
    });
});

// imagemin 压缩图片
gulp.task('distImg', function () {
    return gulp.src(filePath.img)
        .pipe(plugins.changed(filePath.dist_img))
        .pipe(plugins.imagemin())
        .pipe(gulp.dest(filePath.dist_img));
});

// fonts move to build
gulp.task('distStatic', function () {
    filePath.static.map(function ( item, i ) {
        gulp.src(item)
            .pipe(gulp.dest(filePath.dist_static[i]));
    });
});

// pro: run on server 服务器运行
gulp.task('proRun', ['clean'], function () {
    return gulp.start(['distImg', 'webpack', 'distStatic', 'distStaticLibJs', 'distSwig', 'sass', 'distCommon']);
});

//// 监控修改reload浏览器
//gulp.task('allReload', ['sass', 'distCommon', 'webpack', 'distSwig'], function () {
//    reload();
//});

//不运行任务，只启动服务器,有sass/html/common.js的监控
//需要另起webpack任务
gulp.task('simpleServer', function () {
    var proxyOptions = url.parse('http://localhost:9000/public/staticJson/');
    proxyOptions.route = '/api';

    browserSync({
        port: 9000,
        server: {
            baseDir: './build/',
            directory: true,
            middleware: [proxy(proxyOptions)]
        }
    });

    gulp.watch([watchPath.sass], ['sass']);

    gulp.watch([watchPath.swig, watchPath.swigTpm], ['distSwig']);

    gulp.watch(watchPath.lib_common_js, ['distCommon']);
});

// 运行所有任务和启动服务器
//webpack 本身有监控
gulp.task('server', ['distImg', 'distStatic', 'distStaticLibJs', 'distSwig',
    'sass', 'distCommon', 'webpack','simpleServer']);
